/*
 * Copyright © 2022 XXXXXXXXX
 * @Author: zhangxiang
 * @Date: 2022-06-06 15:03:23
 * @LastEditors: zhangxiang
 * @LastEditTime: 2023-02-24 09:39:35
 * @Description:
 *
 */

import { login, getUserInfo } from '@/api/user'
import { removeToken, setToken, getToken } from '@/utils/auth'

const getDefaultState = () => {
  return {
    token: getToken(), // token
    userName: '', // 用户名
    pagePermissions: null // 页面权限
  }
}

const state = getDefaultState() // 初始化

const mutations = {
  /**
   * @description: 重置
   * @return {*}
   */
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  /**
   * @description: 设置用户名
   * @return {*}
   */
  SET_USER_NAME: (state, userName) => {
    state.userName = userName
  },
  /**
   * @description: 设置token
   * @return {*}
   */
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  /**
   * @description: 设置页面权限
   * @return {*}
   */
  SET_PAGE_PERMISSIONS: (state, pagePermissions) => {
    state.pagePermissions = pagePermissions
  }
}

const actions = {
  /**
   * @description: 用户登录
   * @return {*}
   */
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      // 登录接口
      login({
        user: {
          username: username.trim(),
          password: password
        }
      })
        .then((response) => {
          const { data } = response
          const token = data.token ? data.token.token : '' // 获取token
          commit('SET_TOKEN', token) // 存储token
          commit('SET_USER_NAME', data.user ? data.user.username : '') // 存储用户名
          setToken(token) // 存储token
          resolve() // 完成
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  /**
   * @description: 获取用户信息
   * @param {*} commit
   * @param {*} state
   * @return {*}
   */
  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // 调用接口
      getUserInfo()
        .then((response) => {
          const { data } = response

          if (!data) {
            // 数据为空
            return reject('用户认证失败 请先登录')
          }
          const { user, pagePermissions } = data // 获取数据

          commit('SET_USER_NAME', user ? user.username : '') // 存储用户名
          commit('SET_PAGE_PERMISSIONS', pagePermissions || {}) // 存储页面权限

          resolve(data) // 完成
        })
        .catch((error) => {
          reject(error)
        })
    })
  },
  /**
   * @description: 重置
   * @param {*} commit
   * @return {*}
   */
  resetState({ commit }) {
    return new Promise((resolve) => {
      removeToken() // 先移除token
      commit('RESET_STATE') // 重置
      resolve() // 完成
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
